package com.yeskery.nut.web.demo.config;

import com.yeskery.nut.annotation.web.ExceptionHandler;
import com.yeskery.nut.annotation.web.RestControllerAdvice;
import com.yeskery.nut.bind.validator.DataBindValidException;
import com.yeskery.nut.bind.validator.ErrorValidResult;
import com.yeskery.nut.extend.oauth.AuthorizationException;
import com.yeskery.nut.web.demo.common.R;
import com.yeskery.nut.web.demo.exception.AuthException;
import com.yeskery.nut.web.demo.exception.BusinessException;

import java.util.Optional;

/**
 * 全局异常拦截器
 * @author Yeskery
 * 2023/7/28
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(AuthException.class)
    public R<?> validAuthExceptionHandler(AuthException e) {
        return R.fail(e.getMessage());
    }

    @ExceptionHandler(BusinessException.class)
    public R<?> validBusinessExceptionHandler(BusinessException e) {
        return R.fail(e.getMessage());
    }

    @ExceptionHandler(DataBindValidException.class)
    public R<?> validDataBindValidExceptionHandler(DataBindValidException e) {
        Optional<ErrorValidResult> optional = e.getBindingResult().getErrorValidResults().stream().findFirst();
        return R.fail(optional.isPresent() ? optional.get().getMessage() : "请求参数无效");
    }

    @ExceptionHandler(Exception.class)
    public R<?> validExceptionHandler() {
        return R.fail("处理失败");
    }

    @ExceptionHandler(AuthorizationException.class)
    public R<?> validAuthorizationException(AuthorizationException e) {
        return R.fail(e.getMessage());
    }
}
